<template>
  <div class="login">
    <el-card class="login-card" shadow="always">
      <img class="logo" src="@/assets/images/common/logo.png" />
      <div class="login-title">{{ t("login.loginTitle") }}</div>
      <el-form
        v-show="loginType === 'pwd'"
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        class="demo-ruleForm"
        status-icon
        label-width="4vw"
      >
        <el-form-item :label="t('login.userNameLabel')" prop="userName">
          <el-input
            v-model="ruleForm.userName"
            size="large"
            class="login-input"
            :placeholder="t('login.userNamePlaceholder')"
            :prefix-icon="UserFilled"
          />
        </el-form-item>
        <el-form-item :label="t('login.passwordLabel')" prop="password">
          <el-input
            v-model="ruleForm.password"
            type="password"
            show-password
            size="large"
            class="login-input"
            :placeholder="t('login.passwordPlaceholder')"
            :prefix-icon="Checked"
            auto-complete="new-password"
            @keyup.enter="submitForm(ruleFormRef)"
          />
        </el-form-item>
        <el-form-item>
          <div class="btn-box">
            <el-button type="primary" @click="submitForm(ruleFormRef)">{{
              t("login.loginButton")
            }}</el-button>
            <!-- <el-button @click="resetForm(ruleFormRef)">{{
              t("login.resetButton")
            }}</el-button> -->
          </div>
        </el-form-item>
      </el-form>

      <el-form
        v-show="loginType === 'ad'"
        ref="adFormRef"
        :model="adForm"
        :rules="rules"
        class="demo-ruleForm"
        status-icon
        label-width="5vw"
      >
        <el-form-item :label="t('login.domain')" prop="domain">
          <el-input
            v-model="adForm.domain"
            readonly
            size="large"
            prefix-icon="HomeFilled"
          ></el-input>
        </el-form-item>
        <el-form-item :label="t('login.userNameLabel')" prop="userName">
          <el-input
            v-model="adForm.userName"
            size="large"
            class="login-input"
            :placeholder="t('login.userNamePlaceholder')"
            :prefix-icon="UserFilled"
          />
        </el-form-item>
        <el-form-item :label="t('login.passwordLabel')" prop="password">
          <el-input
            v-model="adForm.password"
            type="password"
            show-password
            size="large"
            class="login-input"
            :placeholder="t('login.passwordPlaceholder')"
            :prefix-icon="Checked"
            auto-complete="new-password"
            @keyup.enter="submitAd()"
          />
        </el-form-item>
        <el-form-item>
          <div class="btn-box">
            <el-button
              type="primary"
              @click="submitAd()"
              :loading="adLoading"
              >{{ t("login.loginButton") }}</el-button
            >
          </div>
        </el-form-item>
      </el-form>

      <div v-show="loginType === 'card'" class="login-type">
        <img src="@/assets/images/common/card.png" alt="" class="c-img" />
        <div class="process">
          <div class="p-text">
            {{
              collecting
                ? t("login.cardLoginPrompt")
                : t("login.dataValidationPrompt")
            }}
          </div>
          <div class="p-text-t">
            {{ collecting ? t("login.noKeyboardPrompt") : "" }}
          </div>
        </div>
      </div>

      <el-divider border-style="dashed" />
      <div class="tabs">
        <el-button text @click="changeLoginType('pwd')">{{
          t("login.accountLogin")
        }}</el-button>
        <el-button text @click="changeLoginType('ad')">{{
          t("login.adLogin")
        }}</el-button>
        <el-button text @click="changeLoginType('card')">{{
          t("login.cardLogin")
        }}</el-button>
      </div>
    </el-card>
    <input
      ref="cardRef"
      v-model="cardId"
      type="text"
      class="c-inp"
      @keyup.enter="cardLogin(cardRef)"
      @blur="toFocus"
    />
  </div>
</template>
<script setup name="Login">
import { reactive, ref, watch, toRefs, computed, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { UserFilled, Checked } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import useAuths from "@/hooks/useAuths";
import useStore from "@/store/userStore.js";
import { useI18n } from "vue-i18n";

const store = useStore();
const route = useRoute();
const router = useRouter();
const { t } = useI18n();

const changeLoginType = (type) => {
  data.isCard = isCard;
  data.collecting = true;
  data.loginType = type;
  nextTick(() => {
    if (type == "card") {
      cardRef.value?.focus();
    } else if (type == "pwd") {
      ruleFormRef.value?.clearValidate();
    }
  });
};

const data = reactive({
  isTourist: false,
  redirect: "",
  otherQuery: {},
  isCard: false, // 刷卡登录
  collecting: true, // 校验
  cardId: "",
  loginType: "pwd", //pwd,card,ad
});

const { loginFun, loginByCard, getAdInfo, loginByAd } = useAuths({
  loginReUrl: data.redirect,
});

const adLoading = ref(false);
const ruleFormRef = ref();
const adFormRef = ref();
const cardRef = ref();
const ruleForm = reactive({
  userName: "",
  password: "",
});
const adForm = reactive({
  domain: "",
  userName: "",
  password: "",
});
const rules = reactive({
  userName: [
    {
      required: true,
      message: t("login.userNamePlaceholder"),
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: t("login.passwordPlaceholder"),
      trigger: "blur",
    },
  ],
});

const toFocus = () => {
  if (data.loginType == "card") {
    cardRef.value?.focus();
  }
};

// 密码登录
const login = async (params) => {
  try {
    loginFun(params);
  } catch (error) {
    ElMessage({
      message: error.message,
      type: "error",
      duration: 2000,
    });
  }
};

// 刷卡登录
const cardLogin = async (cardRef) => {
  const value = cardRef.value;
  if (!value) {
    ElMessage({
      message: t("login.noCardMessage"),
      type: "warning",
      duration: 2000,
    });
    return;
  }
  data.collecting = true;
  try {
    await loginByCard({ cardId: value });
    data.collecting = false;
  } catch {
    data.cardId = "";
  }
};

const getOtherQuery = (query) => {
  return Object.keys(query).reduce((acc, cur) => {
    return acc;
  }, {});
};

// 点击登录
const submitForm = async (formEl) => {
  // router.push("/front");
  // return;
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      login(ruleForm);
    }
  });
};

const submitAd = () => {
  adFormRef.value.validate(async (valid) => {
    if (valid) {
      adLoading.value = true;
      await loginByAd(adForm);
      adLoading.value = false;
    }
  });
};

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};

async function getAd() {
  if (adForm.domain || data.loginType != "ad") return;
  try {
    let res = await getAdInfo();
    adForm.domain = res.domain;
    adForm.userName = res.userName;
    if (!adForm.domain) {
      ElMessage.error(t("login.unableToGetAdInfo"));
    }
  } catch (error) {
    console.error(error);
    ElMessage.error(t("login.unableToGetAdInfo"));
  }
}

watch(
  () => route,
  (route) => {
    const { query } = route;

    if (query) {
      data.redirect = query.redirect;
      data.otherQuery = getOtherQuery(query);
    }
  },
  {
    immediate: true,
  }
);

watch(
  () => data.loginType,
  (val) => {
    if (val == "card") {
      nextTick(() => cardRef.value?.focus());
    } else if ((val = "ad")) {
      getAd();
      adForm.password = "";
      cardRef.value?.blur();
    } else {
      cardRef.value?.blur();
    }
  },
  { immediate: true }
);

const { isCard, collecting, cardId, loginType } = toRefs(data);
</script>
<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  // background: url("@/assets/images/common/bg.svg");
  // background-size: 100%;
  // background-position: center;
  // background-repeat: #050f3d;

  .login-card {
    width: 520px;
    min-height: 400px;
    padding: 20px;
    border-radius: 20px;
    // border: 1px solid #f1f1f1;
    border: none;
    background: rgba(0, 80, 164, 0.5);
    color: #fff;
    :deep(.el-card__body) {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }
    .logo {
      width: 200px;
      // background-color: #2e71ed;
    }
    .login-title {
      padding: 30px 0;
      text-align: center;
      font-weight: bold;
      font-size: 24px;
    }
    .login-input {
      width: 300px;
      height: 48px;
    }
    :deep(.el-form-item) {
      display: flex;
      align-items: center;
      padding-bottom: 10px;
      .el-input__icon {
        font-size: 18px;
        // color: #333;
      }
      .el-form-item__label {
        font-size: 16px;
        font-weight: 600;
        color: #fff;
      }
    }
    .login-type {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      .c-img {
        width: 150px;
      }
      .process {
        > div {
          text-align: center;
        }
      }
    }
    .tabs {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: -5px;
      :deep(.el-button) {
        border-radius: 0;
        border-bottom: 1px solid transparent;
        font-size: 16px;
        color: #ccc;
        &:hover {
          border-bottom-color: #409eff;
          color: #409eff;
        }
      }
    }
    .el-divider--horizontal {
      margin: 20px 0 30px;
    }
    .btn-box {
      margin-top: 10px;
      display: flex;
      width: 100%;
      align-items: center;
      justify-content: center;
      :deep(.el-button) {
        width: 100%;
        padding: 18px 24px;
        font-size: 18px;
      }
    }
  }
  .c-inp {
    position: fixed;
    left: -1000000px;
    width: 300px;
    height: 40px;
    border: 1px solid rgb(0, 188, 212);
    border-radius: 6px;
    padding-left: 20px;
  }
}
</style>
